﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class DialogueEntity : MonoBehaviour
{
    public TMP_Text NameText;
    public TMP_Text ContentText;

    [SerializeField]
    public List<string> NameStrings = new List<string>(); //临时这样写一下
    [SerializeField]
    public List<string> ContentStrings = new List<string>();
    public int ContentIndex = 0;
    public string CurNameStr => ContentIndex < NameStrings.Count ? NameStrings[ContentIndex] : string.Empty;
    public string CurSentenceStr => ContentIndex < ContentStrings.Count ? ContentStrings[ContentIndex] : string.Empty;

    public float singleCharTime = 0.1f;
    public byte targetAlpha = 255;
    public byte startAlpha = 0;
    public float targetAlphaFloat = 1f;
    public float startAlphaFloat = 0f;
    public int fadeLen = 4;

    private bool clicked;
    private bool fadeEnding => curFadedTime > curFadingTime;
    private float curFadingTime => singleCharTime * ContentStrings.Count;
    private float curFadedTime;

    public void OnEnable()
    {
        clicked = false;
        curFadedTime = 0f;
        ContentText.text = CurSentenceStr;
        NameText.text = CurNameStr;
    }

    public void Update()
    {
        if(Input.GetKeyUp(KeyCode.KeypadEnter) || Input.GetMouseButtonUp(0))
        {
            clicked = true;
        }
    }

    public void LateUpdate()
    {
        if (clicked)
        {
            if (fadeEnding)
            {
                //切页
                ++ContentIndex;
                curFadedTime = 0f;
                ContentText.text = CurSentenceStr;
                NameText.text = CurNameStr;
            } else
            {
                //直接显示
                curFadedTime = curFadingTime;
                ApplyFade();
            }

            clicked = false;
        }
        if (!fadeEnding)
        {
            ApplyFade();
        }

        ContentText.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32); //通知更新颜色
        curFadedTime += Time.deltaTime;
    }

    /// <summary>
    /// 当前显示的句子长度
    /// </summary>
    private int CurSentenceLen => ContentStrings[ContentIndex].Length;

    /// <summary>
    /// 给整段文字设置默认透明度
    /// </summary>
    /// <param name="targetAlpha"></param>
    private void SetTextAlpha(float targetAlpha)
    {
        var color = ContentText.color;
        color.a = targetAlpha;
        ContentText.color = color;
    }

    /// <summary>
    /// 对整段文字应用透明度渐变
    /// </summary>
    public void ApplyFade()
    {
        //已经显示完了
        if (fadeEnding)
        {
            SetTextAlpha(targetAlphaFloat);
            return;
        }
        //还在显示中
        SetTextAlpha(startAlphaFloat);
        var characterCount = CurSentenceLen;
        var fadingCharacterIndex = Mathf.FloorToInt((curFadedTime / curFadingTime)*characterCount);

        int index = 0;
        for (; index<fadingCharacterIndex; ++index)
        {
            ApplyAlphaToCharAtIndex(index, targetAlpha);
        }
        float ffadeLen = fadeLen;
        for (int increment = 1 ;index < characterCount && index < fadingCharacterIndex + fadeLen; ++index, ++increment)
        {
            ApplyAlphaToCharAtIndex(index, (byte)(startAlpha + (targetAlpha-startAlpha) * (  (ffadeLen - increment)  / ffadeLen  ) ) );
            //Debug.Log((byte)(startAlpha + (targetAlpha - startAlpha) * ((ffadeLen - increment) / ffadeLen)) );
        }
        for (; index < characterCount; ++index)
        {
            ApplyAlphaToCharAtIndex(index, startAlpha);
        }
    }

    /// <summary>
    /// 单独设置每个字的不透明度
    /// 参考：Nova框架的做法
    /// </summary>
    /// <param name="index"></param>
    /// <param name="alpha"></param>
    private void ApplyAlphaToCharAtIndex(int index, byte alpha)
    {
        var characterInfo = ContentText.textInfo.characterInfo;
        if (index >= characterInfo.Length || !characterInfo[index].isVisible) return;

        var meshInfo = ContentText.textInfo.meshInfo;
        var materialIndex = characterInfo[index].materialReferenceIndex;
        var newVertexColors = meshInfo[materialIndex].colors32;
        var vertexIndex = characterInfo[index].vertexIndex;
        newVertexColors[vertexIndex + 0].a = alpha; //TMP_Text的字显示出来是两个面片，直接对面片进行颜色设置就能让插值自动把整个字给修改透明度
        newVertexColors[vertexIndex + 1].a = alpha;
        newVertexColors[vertexIndex + 2].a = alpha;
        newVertexColors[vertexIndex + 3].a = alpha;
    }

}
